package com.ag.main.v1;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * @Description： 读取隐藏在图片里的信息(A)
 * */
public class ShowMessage {
    //暂时把隐写信息长度写死为8，A的ASCII就是01000001，共八位
    private static final int messageLength = 8;

    public static void main(String[] args) {

        try {
            // 读取图片文件
//            File file = new File("./static/33.png");
            File file = new File("./output/33.png");
            BufferedImage image = ImageIO.read(file);
            // 获取图片的宽度和高度
            int width = image.getWidth();
            int height = image.getHeight();
            int messageIndex=0;
            //每个像素的LSB组成一个字符串
            StringBuilder messageBin= new StringBuilder();
            // 遍历每个像素，获取其颜色值
            for (int y = 0; y < height; y++) {
                for (int x = 0; x < width; x++) {
                    Color color = new Color(image.getRGB(x, y));
                    int red = color.getRed();
                    int green = color.getGreen();
                    int blue = color.getBlue();
                    if(messageIndex<messageLength){
                        //按位与，获取LSB
                        messageBin.append(red & 1);
                        messageIndex++;
                        if(messageIndex<messageLength){
                            messageBin.append(green & 1);
                            messageIndex++;
                        }
                        if(messageIndex<messageLength){
                            messageBin.append(blue & 1);
                            messageIndex++;
                        }
                    }
                }
            }
            //将二进制字符串转为字符
            char result = (char) Integer.parseInt(String.valueOf(messageBin),2);
            System.out.println("隐写的内容为："+result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
